#pragma once
#include<iostream>
#include<sys/types.h>
#include<sys/fcntl.h>
#include<string>
#include<sys/stat.h>
#include<unistd.h>
using namespace std;
#define PATH "."
#define NAME "fifo"
#define ERRO(s) \
        {       \
                \
            perror(s); \
            exit(1); \
        }

class Creatfifo
{
public:
    Creatfifo(string path,string name)
    :_path(path),_name(name)
    {
        _fifo_name = _path+'/'+_name;
    }
    void Creat()
    {
        int f = mkfifo(_fifo_name.c_str(),0666);
        if(f<0)
        {
            ERRO("mkfifo");
        }
        else
        {
            cout<<"mkfifo success"<<endl;
        }
    }
    ~Creatfifo()
    {
        unlink(_fifo_name.c_str());
    }
private:
    string _path;
    string _name;
    string _fifo_name;
};
class UseFifo
{
public:
    UseFifo(string path,string name)
    :_path(path),_name(name),_fd(-1)
    {
        _fifo_name=_path+'/'+_name;
    }
    void OpenWrite()
    {
        _fd=open(_fifo_name.c_str(),O_WRONLY);
        if(_fd<0)
        {
            ERRO("open write");
        }
        else
        {
            cout<<"open write success"<<endl;
        }
    }
    void OpenRead()
    {
        _fd=open(_fifo_name.c_str(),O_RDONLY);
        if(_fd<0)
        {
            ERRO("open read");
        }
        else
        {
            cout<<"open read success"<<endl;
        }
    }
    void Read()
    {
        while(true)
        {
            char buf[1024];
            int n=read(_fd,buf,sizeof(buf)-1);
            if(n>0)
            {
                buf[n]='\0';
                cout<<"Client Say# "<<buf<<endl;
            }
            else if(n==0)
            {
                cout<<"client quit!"<<endl;
                break;
            }
            else
            {
                ERRO("read");
            }
        }
    }
    void Write()
    {
        int cnt=1;
        int id = getpid();
        while(true)
        {
            cout<<"Please enter:";
            string message;
	        getline(cin,message);
            write(_fd,message.c_str(),message.size());
        }
    }
    ~UseFifo()
    {
        close(_fd);
    }
private:
    string _path;
    string _name;
    string _fifo_name;
    int _fd;
};